package mail.sender;

import freemarker.template.Configuration;
import mail.MailApplication;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.internet.MimeMessage;

//@ContextConfiguration //指定要读取的配置内容，有@SpringBootTest就无需再配置了
@ExtendWith(SpringExtension.class)
// 使用配置文件中的端口号：SpringBootTest.WebEnvironment.DEFINED_PORT
@SpringBootTest(classes = MailApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
// 只有@Transactional会默认回滚数据，如果不想回滚则：1.去除@Transactional和@Rollback；2.设置@Transactional和@Rollback(false)
@Transactional
@Rollback(false)
@ActiveProfiles("mail")
public class JavaMailTest {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private Configuration configuration;

    @Test
    public void testSendEmail() throws Exception {
        // create template and data to send
//    Template template = configuration.getTemplate("templates/notice.ftl");
//    Map<String, Object> mailData = new HashMap<>();
//    mailData.put("taskName", "ita spring boot");
//    mailData.put("endTime", LocalDateTime.now());
//    StringWriter stringWriter = new StringWriter();
//    template.process(mailData, stringWriter);
//    String html = stringWriter.getBuffer().toString();

        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom("820448595@qq.com");
        helper.setTo(new String[]{"harper.h.p.zhang@cargosmart.com"});
        helper.setText("hello world", false);
        javaMailSender.send(message);
    }
}
